<script id="gouraud-shader-vs" type="x-shader/x-vertex">
    precision mediump float;
    
    attribute vec3 inPos;
    attribute vec3 inNV;
    attribute vec3 inCol;
    
    varying vec3 vertPos;
    varying vec3 vertNV;
    varying vec3 vertCol;
    
    uniform mat4 u_projectionMat44;
    uniform mat4 u_viewMat44;
    uniform mat4 u_modelMat44;
  
    struct TLightSource
    {
        vec3  lightDir;
        vec3  ambient;
        vec3  diffuse;
        vec3  specular;
        float shininess;
    };
  
    uniform TLightSource u_lightSource;
    
    vec3 Light( vec3 eyeV, vec3 N )
    {
        vec3  lightCol  = u_lightSource.ambient;
        vec3  L         = normalize( -u_lightSource.lightDir );
        float NdotL     = max( 0.0, dot( N, L ) );
        lightCol       += NdotL * u_lightSource.diffuse;
        vec3  H         = normalize( eyeV + L );
        float NdotH     = max( 0.0, dot( N, H ) );
        float kSpecular = ( u_lightSource.shininess + 2.0 ) * pow( NdotH, u_lightSource.shininess ) / ( 2.0 * 3.14159265 );
        lightCol       += kSpecular * u_lightSource.specular;
        return lightCol; 
    }
    
    void main()
    {
        vec3 modelNV  = mat3( u_modelMat44 ) * normalize( inNV );
        vertNV        = mat3( u_viewMat44 ) * modelNV;
        vec4 modelPos = u_modelMat44 * vec4( inPos, 1.0 );
        vec4 viewPos  = u_viewMat44 * modelPos;
        vertPos       = viewPos.xyz / viewPos.w;
        vec3 eyeV     = normalize( -vertPos );
        vec3 normalV  = normalize( vertNV );
        vertCol       = inCol * Light( eyeV, normalV );
        gl_Position   = u_projectionMat44 * viewPos;
    }
    </script>
    
    <script id="gouraud-shader-fs" type="x-shader/x-fragment">
    precision mediump float;
    
    varying vec3 vertPos;
    varying vec3 vertNV;
    varying vec3 vertCol;
    
    void main()
    {
        gl_FragColor = vec4( vertCol, 1.0 );
    }
    </script>
  
  <script id="phong-shader-vs" type="x-shader/x-vertex">
  precision mediump float;
  
  attribute vec3 inPos;
  attribute vec3 inNV;
  attribute vec3 inCol;
  
  varying vec3 vertPos;
  varying vec3 vertNV;
  varying vec3 vertCol;
  
  uniform mat4 u_projectionMat44;
  uniform mat4 u_viewMat44;
  uniform mat4 u_modelMat44;
  
  void main()
  {
    vec3 modelNV  = mat3( u_modelMat44 ) * normalize( inNV );
    vertNV        = mat3( u_viewMat44 ) * modelNV;
    vertCol       = inCol;
    vec4 modelPos = u_modelMat44 * vec4( inPos, 1.0 );
    vec4 viewPos  = u_viewMat44 * modelPos;
    vertPos       = viewPos.xyz / viewPos.w;
    gl_Position   = u_projectionMat44 * viewPos;
  }
  </script>
  
  <script id="phong-shader-fs" type="x-shader/x-fragment">
  precision mediump float;
  
  varying vec3 vertPos;
  varying vec3 vertNV;
  varying vec3 vertCol;
  
  struct TLightSource
  {
    vec3  lightDir;
    vec3  ambient;
    vec3  diffuse;
    vec3  specular;
    float shininess;
  };
  
  uniform TLightSource u_lightSource;
  
  vec3 Light( vec3 eyeV, vec3 N )
  {
    vec3  lightCol  = u_lightSource.ambient;
    vec3  L         = normalize( -u_lightSource.lightDir );
    float NdotL     = max( 0.0, dot( N, L ) );
    lightCol       += NdotL * u_lightSource.diffuse;
    vec3  H         = normalize( eyeV + L );
    float NdotH     = max( 0.0, dot( N, H ) );
    float kSpecular = ( u_lightSource.shininess + 2.0 ) * pow( NdotH, u_lightSource.shininess ) / ( 2.0 * 3.14159265 );
    lightCol       += kSpecular * u_lightSource.specular;
    return lightCol; 
  }
  
  void main()
  {
    vec3 eyeV    = normalize( -vertPos );
    vec3 normalV = normalize( vertNV );
    vec3 color   = vertCol * Light( eyeV, normalV );
    gl_FragColor = vec4( color, 1.0 );
  }
</script>

<style>
html,body { margin: 0; overflow: hidden; }
#gui { position : absolute; top : 0; left : 0; font-size : large; }
#ref-link { position : absolute; bottom : 0; left : 0; font-size : large; }  
</style>

<body>

<div>
    <form id="gui" name="inputs">
        <table>
            <tr> <td> <font color= #CCF>ambient</font> </td> 
                    <td> <input type="color" id="ambient_col"></td>
                    <td> <input type="range" id="ambient" min="0" max="100" value="0"/></td> </tr>
            <tr> <td> <font color= #CCF>diffuse</font> </td> 
                    <td> <input type="color" id="diffuse_col"></td>
                    <td> <input type="range" id="diffuse" min="0" max="100" value="0"/></td> </tr>
            <tr> <td> <font color= #CCF>specular</font> </td> 
                    <td> <input type="color" id="specular_col"></td>
                    <td> <input type="range" id="specular" min="0" max="100" value="0"/></td> </tr>
            <tr> <td> <font color= #CCF>shininess</font> </td> 
                    <td> <input type="range" id="shininess" min="0" max="100" value="0"/></td> </tr>
            <tr> <td> <font color= #CCF>form</font> </td> <td>
                <select id="form">>
                    <option value="0">cube</option>
                    <option value="1">sphere</option>
                    <option value="2">torus</option>
                </select>
            </td> </tr>
            <tr> <td> <font color= #CCF>shading</font> </td> <td>
                <select id="shading">>
                    <option value="0">gouraud</option>
                    <option value="1">phong</option>
                </select>
            </td> </tr>
        </table>
    </form>
</div>

<div id="ref-link">
<a href="https://stackoverflow.com/questions/8421778/glsl-fixed-function-fragment-program-replacement/45716107#45716107"> 
<font color= #CCF>GLSL fixed function fragment program replacement</font>
</a>
<br/>
<a href="https://stackoverflow.com/questions/49966240/phong-and-gouraud-shading-webgl/49966346#49966346"> 
<font color= #CCF>Phong and Gouraud Shading WebGL</font>
</a>
<br/>
<a href="https://stackoverflow.com/questions/48523723/per-vertex-diffuse-and-specular-shader/48528327#48528327"> 
<font color= #CCF>Per Vertex Diffuse and Specular Shader</font>
</a>
</div>

<canvas id="canvas" style="border: none;"></canvas>

<script type="text/javascript">

(function loadscene() {

var resize, gl, gouraudDraw, phongDraw, vp_size;
var bufCube, bufSphere, bufTorus;
var sliderScale = 100.0;

function render(deltaMS){

    var ambient_col = hexToRgb( document.getElementById( "ambient_col" ).value );
    var diffuse_col = hexToRgb( document.getElementById( "diffuse_col" ).value );
    var specular_col = hexToRgb( document.getElementById( "specular_col" ).value );
    var ambient = document.getElementById( "ambient" ).value / sliderScale;
    var diffuse = document.getElementById( "diffuse" ).value / sliderScale;
    var specular = document.getElementById( "specular" ).value / sliderScale;
    var shininess = document.getElementById( "shininess" ).value;
    var ambientCol = [ambient_col.r*ambient/256.0, ambient_col.g*ambient/256.0, ambient_col.b*ambient/256.0];
    var diffuseCol = [diffuse_col.r*diffuse/256.0, diffuse_col.g*diffuse/256.0, diffuse_col.b*diffuse/256.0];
    var specularCol = [specular_col.r*specular/256.0, specular_col.g*specular/256.0, specular_col.b*specular/256.0];
    var form = document.getElementById( "form" ).value;
    var shading = document.getElementById( "shading" ).value;

    vp_size = [canvas.width, canvas.height];
    camera.Update( vp_size );
        
    gl.viewport( 0, 0, canvas.width, canvas.height );    
    gl.enable( gl.DEPTH_TEST );
    gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );

    // setup view projection and model
    var prjMat = camera.Perspective();
    var viewMat = camera.Orbit();
    var modelMat = IdentM44();
    modelMat = camera.AutoModelMatrix();
    
    gl.enable(gl.CULL_FACE);
    gl.cullFace(gl.BACK);
    //gl.frontFace(gl.CW);
    gl.frontFace(gl.CCW);
    
    var progDraw = shading == 0 ? gouraudDraw : phongDraw;;
    // set up draw shader
    ShProg.Use( progDraw );
    ShProg.SetM44( progDraw, "u_projectionMat44", prjMat );
    ShProg.SetM44( progDraw, "u_viewMat44", viewMat );
    ShProg.SetF3( progDraw, "u_lightSource.lightDir", [-1.0, -0.5, -2.0] )
    ShProg.SetF3( progDraw, "u_lightSource.ambient", ambientCol )
    ShProg.SetF3( progDraw, "u_lightSource.diffuse", diffuseCol )
    ShProg.SetF3( progDraw, "u_lightSource.specular", specularCol )
    ShProg.SetF1( progDraw, "u_lightSource.shininess", shininess )
    ShProg.SetM44( progDraw, "u_modelMat44", modelMat );
    
    // draw scene
    bufObj = form == 0 ? bufCube : form == 1 ? bufSphere : bufTorus;
    VertexBuffer.Draw( bufObj );
   
    requestAnimationFrame(render);
}

function resize() {
    //vp_size = [gl.drawingBufferWidth, gl.drawingBufferHeight];
    vp_size = [window.innerWidth, window.innerHeight];
    //vp_size = [256, 256]
    canvas.width = vp_size[0];
    canvas.height = vp_size[1];
    gl.viewport( 0, 0, vp_size[0], vp_size[1] );
}

function initScene() {

    document.getElementById( "ambient_col" ).value = "#FFFFFF";
    document.getElementById( "diffuse_col" ).value = "#FFFFFF";
    document.getElementById( "specular_col" ).value = "#FFFFFF";
    document.getElementById( "ambient" ).value = 0.2 * sliderScale;
    document.getElementById( "diffuse" ).value = 0.6 * sliderScale;
    document.getElementById( "specular" ).value = 0.8 * sliderScale;
    document.getElementById( "shininess" ).value = 25.0;
    document.getElementById( "shading" ).value = 0;
    document.getElementById( "form" ).value = 1;

    canvas = document.getElementById( "canvas");
    gl = canvas.getContext( "experimental-webgl" );
    if ( !gl )
      return null;

    gouraudDraw = ShProg.Create( 
      [ { source : "gouraud-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "gouraud-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    if ( gouraudDraw.progObj == 0 )
      return;  
    gouraudDraw.inPos = gl.getAttribLocation( gouraudDraw.progObj, "inPos" );
    gouraudDraw.inNV  = gl.getAttribLocation( gouraudDraw.progObj, "inNV" );
    gouraudDraw.inCol = gl.getAttribLocation( gouraudDraw.progObj, "inCol" );

    phongDraw = ShProg.Create( 
      [ { source : "phong-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "phong-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    if ( phongDraw.progObj == 0 )
      return;
    phongDraw.inPos = gl.getAttribLocation( phongDraw.progObj, "inPos" );
    phongDraw.inNV  = gl.getAttribLocation( phongDraw.progObj, "inNV" );
    phongDraw.inCol = gl.getAttribLocation( phongDraw.progObj, "inCol" );
    
    // create cube
    var cubePos = [
        -1.0, -1.0,  1.0,  1.0, -1.0,  1.0,  1.0,  1.0,  1.0, -1.0,  1.0,  1.0,
        -1.0, -1.0, -1.0,  1.0, -1.0, -1.0,  1.0,  1.0, -1.0, -1.0,  1.0, -1.0 ];
    var cubeCol = [ 1.0, 0.0, 0.0, 1.0, 0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ];
    var cubeHlpInx = [ 0, 1, 2, 3, 1, 5, 6, 2, 5, 4, 7, 6, 4, 0, 3, 7, 3, 2, 6, 7, 1, 0, 4, 5 ]; 
    var cubePosData = [];
    for ( var i = 0; i < cubeHlpInx.length; ++ i ) {
        cubePosData.push( cubePos[cubeHlpInx[i]*3], cubePos[cubeHlpInx[i]*3+1], cubePos[cubeHlpInx[i]*3+2] );
    }
    var cubeNVData = [];
    for ( var i1 = 0; i1 < cubeHlpInx.length; i1 += 4 ) {
        var nv = [0, 0, 0];
        for ( i2 = 0; i2 < 4; ++ i2 ) {
            var i = i1 + i2;
            nv[0] += cubePosData[i*3]; nv[1] += cubePosData[i*3+1]; nv[2] += cubePosData[i*3+2];
        }
        for ( i2 = 0; i2 < 4; ++ i2 )
          cubeNVData.push( nv[0], nv[1], nv[2] );
    }
    var cubeColData = [];
    for ( var is = 0; is < 6; ++ is ) {
        for ( var ip = 0; ip < 4; ++ ip ) {
           cubeColData.push( cubeCol[is*3], cubeCol[is*3+1], cubeCol[is*3+2] ); 
        }
    }
    var cubeInxData = [];
    for ( var i = 0; i < cubeHlpInx.length; i += 4 ) {
        cubeInxData.push( i, i+1, i+2, i, i+2, i+3 );
    }
    bufCube = VertexBuffer.Create(
    [ { data : cubePosData, attrSize : 3, attrLoc : gouraudDraw.inPos },
      { data : cubeNVData, attrSize : 3, attrLoc : gouraudDraw.inNV },
      { data : cubeColData, attrSize : 3, attrLoc : gouraudDraw.inCol } ],
      cubeInxData );

    // create sphere
    var layer_size = 16, circum_size = 32;
    var rad_circum = 1.0;
    var rad_tube = 0.5;
    var cols = [0.75, 0.75, 0.75];
    var sphere_pts = [];
    var sphere_nv = [];
    var sphere_col = [];
    sphere_pts.push( 0.0, 0.0, -2.0 );
    sphere_nv.push( 0.0, 0.0, -1.0 );
    sphere_col.push( cols[0], cols[1], cols[2] );
    for ( var i_l = 1; i_l < layer_size; ++ i_l ) {
        var angH = (1.0 - i_l / layer_size) * Math.PI;
        var h = Math.cos( angH );
        var r = Math.sin( angH );
        for ( var i_c = 0; i_c < circum_size; ++ i_c ) {
            var circumX = Math.cos(2 * Math.PI * i_c / circum_size);
            var circumY = Math.sin(2 * Math.PI * i_c / circum_size);
            sphere_pts.push( r * circumX * 2.0, r * circumY * 2.0, h * 2.0 );
            sphere_nv.push( r * circumX, r * circumY, h );
            sphere_col.push( cols[0], cols[1], cols[2] );
        }
    }
    sphere_pts.push( 0.0, 0.0, 2.0 );
    sphere_nv.push( 0.0, 0.0, 1.0 );
    sphere_col.push( cols[0], cols[1], cols[2] );
    var sphere_inx = [];
    for ( var i_c = 0; i_c < circum_size; ++ i_c ) {
        sphere_inx.push( i_c+1, 0, (i_c+1) % circum_size + 1 )
    }
    for ( var i_l = 0; i_l < layer_size-2; ++ i_l ) {
        var l1 = i_l * circum_size + 1;
        var l2 = (i_l+1) * circum_size + 1
        for ( var i_c = 0; i_c < circum_size; ++ i_c ) {
            var i_n = (i_c+1) % circum_size;
            sphere_inx.push( l1+i_c, l1+i_n, l2+i_c, l1+i_n, l2+i_n, l2+i_c );
        }
    }
    for ( var i_c = 0; i_c < circum_size; ++ i_c ) {
        var i_start = 1 + (layer_size-2) * circum_size;
        var i_n = (i_c+1) % circum_size;
        sphere_inx.push( i_start + i_c, i_start + i_n, sphere_pts.length/3-1 );
    }
    bufSphere = VertexBuffer.Create(
    [ { data : sphere_pts, attrSize : 3, attrLoc : gouraudDraw.inPos },
      { data : sphere_nv, attrSize : 3, attrLoc : gouraudDraw.inNV },
      { data : sphere_col, attrSize : 3, attrLoc : gouraudDraw.inCol } ],
      sphere_inx );

    // create torus
    var circum_size = 32, tube_size = 32;
    var rad_circum = 1.4;
    var rad_tube = 0.6;
    var torus_pts = [];
    var torus_nv = [];
    var torus_col = [];
    var torus_inx = [];
    var col = [1, 0.5, 0.0];
    for ( var i_c = 0; i_c < circum_size; ++ i_c ) {
        var center = [
            Math.cos(2 * Math.PI * i_c / circum_size),
            Math.sin(2 * Math.PI * i_c / circum_size) ]
        for ( var i_t = 0; i_t < tube_size; ++ i_t ) {
            var tubeX = Math.cos(2 * Math.PI * i_t / tube_size)
            var tubeY = Math.sin(2 * Math.PI * i_t / tube_size)
            var pt = [
                center[0] * ( rad_circum + tubeX * rad_tube ),
                center[1] * ( rad_circum + tubeX * rad_tube ),
                tubeY * rad_tube ]
            var nv = [ pt[0] - center[0] * rad_tube, pt[1] - center[1] * rad_tube, tubeY * rad_tube ]
            torus_pts.push( pt[0], pt[1], pt[2] );
            torus_nv.push( nv[0], nv[1], nv[2] );
            torus_col.push( col[0], col[1], col[2] );
            var i_cn = (i_c+1) % circum_size
            var i_tn = (i_t+1) % tube_size
            var i_c0 = i_c * tube_size; 
            var i_c1 = i_cn * tube_size; 
            torus_inx.push( i_c0+i_t, i_c1+i_t, i_c0+i_tn, i_c0+i_tn, i_c1+i_t, i_c1+i_tn )
        }
    }
    bufTorus = VertexBuffer.Create(
    [ { data : torus_pts, attrSize : 3, attrLoc : gouraudDraw.inPos },
      { data : torus_nv, attrSize : 3, attrLoc : gouraudDraw.inNV },
      { data : torus_col, attrSize : 3, attrLoc : gouraudDraw.inCol } ],
      torus_inx );

    camera = new Camera( [0, 3, 0.0], [0, 0, 0], [0, 0, 1], 90, vp_size, 0.5, 100 );  
      
    window.onresize = resize;
    resize();
    requestAnimationFrame(render);
}

function Fract( val ) { 
    return val - Math.trunc( val );
}
function CalcAng( deltaTime, intervall ) {
    return Fract( deltaTime / (1000*intervall) ) * 2.0 * Math.PI;
}
function CalcMove( deltaTime, intervall, range ) {
    var pos = self.Fract( deltaTime / (1000*intervall) ) * 2.0
    var pos = pos < 1.0 ? pos : (2.0-pos)
    return range[0] + (range[1] - range[0]) * pos;
}    
function EllipticalPosition( a, b, angRag ) {
    var a_b = a * a - b * b
    var ea = (a_b <= 0) ? 0 : Math.sqrt( a_b );
    var eb = (a_b >= 0) ? 0 : Math.sqrt( -a_b );
    return [ a * Math.sin( angRag ) - ea, b * Math.cos( angRag ) - eb, 0 ];
}

function IdentM44() { return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; }

function RotateAxis(matA, angRad, axis) {
    var aMap = [ [1, 2], [2, 0], [0, 1] ];
    var a0 = aMap[axis][0], a1 = aMap[axis][1]; 
    var sinAng = Math.sin(angRad), cosAng = Math.cos(angRad);
    var matB = matA.slice(0);
    for ( var i = 0; i < 16; ++ i ) matB[i] = matA[i];
    for ( var i = 0; i < 3; ++ i ) {
        matB[a0*4+i] = matA[a0*4+i] * cosAng + matA[a1*4+i] * sinAng;
        matB[a1*4+i] = matA[a0*4+i] * -sinAng + matA[a1*4+i] * cosAng;
    }
    return matB;
}

function Rotate(matA, angRad, axis) {
    var s = Math.sin(angRad), c = Math.cos(angRad);
    var x = axis[0], y = axis[1], z = axis[2]; 
    matB = [
        x*x*(1-c)+c,   x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0,
        y*x*(1-c)+z*s, y*y*(1-c)+c,   y*z*(1-c)-x*s, 0,
        z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c,   0,
        0,             0,             0,             1 ];
    return Multiply(matA, matB);
}    

function Multiply(matA, matB) {
    matC = IdentM44();
    for (var i0=0; i0<4; ++i0 )
        for (var i1=0; i1<4; ++i1 )
            matC[i0*4+i1] = matB[i0*4+0] * matA[0*4+i1] + matB[i0*4+1] * matA[1*4+i1] + matB[i0*4+2] * matA[2*4+i1] + matB[i0*4+3] * matA[3*4+i1]  
    return matC;
}

function Cross( a, b ) { return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], 0.0 ]; }
function Dot( a, b ) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }
function Normalize( v ) {
    var len = Math.sqrt( v[0] * v[0] + v[1] * v[1] + v[2] * v[2] );
    return [ v[0] / len, v[1] / len, v[2] / len ];
}

Camera = function( pos, target, up, fov_y, vp, near, far ) {
this.Time = function() { return Date.now(); }
this.pos = pos;
this.target = target;
this.up = up;
this.fov_y = fov_y;
this.vp = vp;
this.near = near;
this.far = far;
this.orbit_mat = this.current_orbit_mat = this.model_mat = this.current_model_mat = IdentM44();
this.mouse_drag = this.auto_spin = false;
this.auto_rotate = true;
this.mouse_start = [0, 0];
this.mouse_drag_axis = [0, 0, 0];
this.mouse_drag_angle = 0;
this.mouse_drag_time = 0;
this.drag_start_T = this.rotate_start_T = this.Time();
this.Ortho = function() {
    var fn = this.far + this.near;
    var f_n = this.far - this.near;
    var w = this.vp[0];
    var h = this.vp[1];
    return [
        2/w, 0,   0,       0,
        0,   2/h, 0,       0,
        0,   0,   -2/f_n,  0,
        0,   0,   -fn/f_n, 1 ];
};  
this.Perspective = function() {
    var n = this.near;
    var f = this.far;
    var fn = f + n;
    var f_n = f - n;
    var r = this.vp[0] / this.vp[1];
    var t = 1 / Math.tan( Math.PI * this.fov_y / 360 );
    return [
        t/r, 0, 0,          0,
        0,   t, 0,          0,
        0,   0, -fn/f_n,   -1,
        0,   0, -2*f*n/f_n, 0 ];
}; 
this.LookAt = function() {
    var mz = Normalize( [ this.pos[0]-this.target[0], this.pos[1]-this.target[1], this.pos[2]-this.target[2] ] );
    var mx = Normalize( Cross( this.up, mz ) );
    var my = Normalize( Cross( mz, mx ) );
    var tx = Dot( mx, this.pos );
    var ty = Dot( my, this.pos );
    var tz = Dot( [-mz[0], -mz[1], -mz[2]], this.pos ); 
    return [mx[0], my[0], mz[0], 0, mx[1], my[1], mz[1], 0, mx[2], my[2], mz[2], 0, tx, ty, tz, 1]; 
};
this.Orbit = function() {
    return Multiply(this.LookAt(), this.OrbitMatrix());
}; 
this.OrbitMatrix = function() {
    return (this.mouse_drag || (this.auto_rotate && this.auto_spin)) ? Multiply(this.current_orbit_mat, this.orbit_mat) : this.orbit_mat;
};
this.AutoModelMatrix = function() {
    return this.auto_rotate ? Multiply(this.current_model_mat, this.model_mat) : this.model_mat;
};
this.Update = function(vp_size) {
    if (vp_size)
        this.vp = vp_size;
    var current_T = this.Time();
    this.current_model_mat = IdentM44()
    if (this.mouse_drag) {
        this.current_orbit_mat = Rotate(IdentM44(), this.mouse_drag_angle, this.mouse_drag_axis);
    } else if (this.auto_rotate) {
        if (this.auto_spin ) {
            if (this.mouse_drag_time > 0 ) {
                var angle = this.mouse_drag_angle * (current_T - this.rotate_start_T) / this.mouse_drag_time;
                this.current_orbit_mat = Rotate(IdentM44(), angle, this.mouse_drag_axis);
            }
        } else {
            var auto_angle_x = Fract( (current_T - this.rotate_start_T) / 13000.0 ) * 2.0 * Math.PI;
            var auto_angle_y = Fract( (current_T - this.rotate_start_T) / 17000.0 ) * 2.0 * Math.PI;
            this.current_model_mat = RotateAxis( this.current_model_mat, auto_angle_x, 0 );
            this.current_model_mat = RotateAxis( this.current_model_mat, auto_angle_y, 1 );
        }
    }
};
this.ChangeMotionMode = function(drag, spin, auto ) {
    var new_drag = drag;
    var new_auto = new_drag ? false : auto;
    var new_spin = new_auto ? spin : false;
    change = this.mouse_drag != new_drag || this.auto_rotate != new_auto || this.auto_spin != new_spin; 
    if (!change)
        return;
    if (new_drag && !this.mouse_drag) {
        this.drag_start_T = this.Time();
        this.mouse_drag_angle = 0.0;
        this.mouse_drag_time = 0;
    }
    if (new_auto && !this.auto_rotate)
        this.rotate_start_T = this.Time();
    this.mouse_drag = new_drag; 
    this.auto_rotate = new_auto;  
    this.auto_spin = new_spin;
    this.orbit_mat = Multiply(this.current_orbit_mat, this.orbit_mat);
    this.current_orbit_mat = IdentM44();
    this.model_mat = Multiply(this.current_model_mat, this.model_mat);
    this.current_model_mat = IdentM44();
};
this.OnMouseDown = function( event ) {
    var rect = gl.canvas.getBoundingClientRect();
    if ( event.clientX < rect.left || event.clientX > rect.right ) return;
    if ( event.clientY < rect.top || event.clientY > rect.bottom ) return;
    if (event.button == 0) { // left button
        this.mouse_start = [event.clientX, event.clientY]; 
        this.ChangeMotionMode( true, false, false );
    }
};
this.OnMouseUp = function( event ) {
    if (event.button == 0) { // left button
        this.ChangeMotionMode( false, true, true );
    } else if (event.button == 1) {// middle button
        this.ChangeMotionMode( false, false, !this.auto_rotate );
    }
};
this.OnMouseMove = function( event ) {
    var dx = (event.clientX-this.mouse_start[0]) / this.vp[0];
    var dy = (event.clientY-this.mouse_start[1]) / this.vp[1];
    var len = Math.sqrt(dx*dx + dy*dy);
    if (this.mouse_drag && len > 0) {
        this.mouse_drag_angle = Math.PI*len;
        this.mouse_drag_axis = [dy/len, 0, -dx/len];
        this.mouse_drag_time = this.Time() - this.drag_start_T;
    }
};

this.domElement = document;
var cam = this;
//this.domElement.addEventListener( 'contextmenu', function(e) { event.preventDefault(); }, false );
this.domElement.addEventListener( 'mousedown', function(e) { cam.OnMouseDown(e) }, false );
this.domElement.addEventListener( 'mouseup', function(e) { cam.OnMouseUp(e) }, false );
this.domElement.addEventListener( 'mousemove', function(e) { cam.OnMouseMove(e) }, false );
//this.domElement.addEventListener( 'mousewheel', hid_events.onMouseWheel, false );
//this.domElement.addEventListener( 'DOMMouseScroll', hid_events.onMouseWheel, false ); // firefox
}

var ShProg = {
Create: function (shaderList) {
    var shaderObjs = [];
    for (var i_sh = 0; i_sh < shaderList.length; ++i_sh) {
        var shderObj = this.Compile(shaderList[i_sh].source, shaderList[i_sh].stage);
        if (shderObj) shaderObjs.push(shderObj);
    }
    var prog = {}
    prog.progObj = this.Link(shaderObjs)
    if (prog.progObj) {
        prog.attrInx = {};
        var noOfAttributes = gl.getProgramParameter(prog.progObj, gl.ACTIVE_ATTRIBUTES);
        for (var i_n = 0; i_n < noOfAttributes; ++i_n) {
            var name = gl.getActiveAttrib(prog.progObj, i_n).name;
            prog.attrInx[name] = gl.getAttribLocation(prog.progObj, name);
        }
        prog.uniLoc = {};
        var noOfUniforms = gl.getProgramParameter(prog.progObj, gl.ACTIVE_UNIFORMS);
        for (var i_n = 0; i_n < noOfUniforms; ++i_n) {
            var name = gl.getActiveUniform(prog.progObj, i_n).name;
            prog.uniLoc[name] = gl.getUniformLocation(prog.progObj, name);
        }
    }
    return prog;
},
AttrI: function (prog, name) { return prog.attrInx[name]; },
UniformL: function (prog, name) { return prog.uniLoc[name]; },
Use: function (prog) { gl.useProgram(prog.progObj); },
SetI1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1i(prog.uniLoc[name], val); },
SetF1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1f(prog.uniLoc[name], val); },
SetF2: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform2fv(prog.uniLoc[name], arr); },
SetF3: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform3fv(prog.uniLoc[name], arr); },
SetF4: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform4fv(prog.uniLoc[name], arr); },
SetM33: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix3fv(prog.uniLoc[name], false, mat); },
SetM44: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix4fv(prog.uniLoc[name], false, mat); },
Compile: function (source, shaderStage) {
    var shaderScript = document.getElementById(source);
    if (shaderScript)
        source = shaderScript.text;
    var shaderObj = gl.createShader(shaderStage);
    gl.shaderSource(shaderObj, source);
    gl.compileShader(shaderObj);
    var status = gl.getShaderParameter(shaderObj, gl.COMPILE_STATUS);
    if (!status) alert(gl.getShaderInfoLog(shaderObj));
    return status ? shaderObj : null;
},
Link: function (shaderObjs) {
    var prog = gl.createProgram();
    for (var i_sh = 0; i_sh < shaderObjs.length; ++i_sh)
        gl.attachShader(prog, shaderObjs[i_sh]);
    gl.linkProgram(prog);
    status = gl.getProgramParameter(prog, gl.LINK_STATUS);
    if ( !status ) alert(gl.getProgramInfoLog(prog));
    return status ? prog : null;
} };

var VertexBuffer = {
Create: function(attribs, indices, type) {
    var buffer = { buf: [], attr: [], inx: gl.createBuffer(), inxLen: indices.length, primitive_type: type ? type : gl.TRIANGLES };
    for (var i=0; i<attribs.length; ++i) {
        buffer.buf.push(gl.createBuffer());
        buffer.attr.push({ size : attribs[i].attrSize, loc : attribs[i].attrLoc, no_of: attribs[i].data.length/attribs[i].attrSize });
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer.buf[i]);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array( attribs[i].data ), gl.STATIC_DRAW);
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, null);
    if ( buffer.inxLen > 0 ) {
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer.inx);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( indices ), gl.STATIC_DRAW);
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
    }
    return buffer;
},
Draw: function(bufObj) {
    for (var i=0; i<bufObj.buf.length; ++i) {
        gl.bindBuffer(gl.ARRAY_BUFFER, bufObj.buf[i]);
        gl.vertexAttribPointer(bufObj.attr[i].loc, bufObj.attr[i].size, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray( bufObj.attr[i].loc);
    }
    if ( bufObj.inxLen > 0 ) {
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufObj.inx);
        gl.drawElements(bufObj.primitive_type, bufObj.inxLen, gl.UNSIGNED_SHORT, 0);
        gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
    }
    else
        gl.drawArrays(bufObj.primitive_type, 0, bufObj.attr[0].no_of );
    for (var i=0; i<bufObj.buf.length; ++i)
        gl.disableVertexAttribArray(bufObj.attr[i].loc);
    gl.bindBuffer( gl.ARRAY_BUFFER, null );
} };

function hexToRgb (hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

initScene();

})();

</script>

</body>